package cn.zbzcode.mq._01helloworld;

import cn.zbzcode.mq.ConnectionUtil;
import com.rabbitmq.client.*;

import java.io.IOException;

public class Rev {
    //队列的名字
    private static final String QUEUE_HELLO = "queue_hello5";
    public static void main(String[] args) {
        try {
            //1.创建链接
            Connection connection = ConnectionUtil.getConnection();

            //2.创建通道
            final Channel channel = connection.createChannel();

            //3.声明队列
            channel.queueDeclare(QUEUE_HELLO, true, false, false, null);


            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope,
                                           AMQP.BasicProperties properties, byte[] body)throws IOException {

                    //交换机
                    String exchange = envelope.getExchange();
                    System.out.println("exchange:"+exchange);
                    //路由key
                    String routingKey = envelope.getRoutingKey();
                    System.out.println("routingKey:"+routingKey);
                    //消息id
                    long deliveryTag = envelope.getDeliveryTag();
                    System.out.println("deliveryTag:"+deliveryTag);
                    //消息内容
                    String msg = new String(body, "utf8");
                    System.out.println("收到消息:" + msg);
                    //System.out.println(1 / 0);

                    //手动签收一下
                    channel.basicAck(deliveryTag, false);
                }
            };
            //4.接受消息 :队列 ； 签收方式(true:自动签收)
            channel.basicConsume(QUEUE_HELLO, false,consumer);


        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}